package com.example.administrator.basedemos.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.example.administrator.basedemos.R;
import com.example.administrator.basedemos.base.BaseActivity;
import com.example.administrator.basedemos.utils.AutoCheck;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.OnClick;

/**
 * 创建者     ZCL
 * 创建时间   2018/5/10 13:15
 * 描述	      ${TODO}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */

public class AiVoiceRecorgnitionActivity extends BaseActivity {


    /*
     * 本Activity中是否需要调用离线命令词功能。根据此参数，判断是否需要调用SDK的ASR_KWS_LOAD_ENGINE事件
     */
    protected boolean enableOffline = false;


    /**
     * 控制UI按钮的状态
     */
    protected int status;


    private boolean logTime = true;
    private EventManager mAsr;

    @Override
    public void initView() {
        // this是Activity或其它Context类
        mAsr = EventManagerFactory.create(this, "asr");
    }

    @Override
    public void initData() {
        initPermission();
    }

    @OnClick({R.id.voice_start})
    public void OnClik(View v) {
        switch (v.getId()) {
            case R.id.voice_start:
                start();
                break;

            default:
                break;
        }
    }


    /**
     * 测试参数填在这里
     */
    private void start() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        String event = null;
        event = SpeechConstant.ASR_START; // 替换成测试的event

        if (enableOffline) {
            params.put(SpeechConstant.DECODER, 2);
        }
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
        // params.put(SpeechConstant.NLU, "enable");
        // params.put(SpeechConstant.VAD_ENDPOINT_TIMEOUT, 0); // 长语音
        // params.put(SpeechConstant.IN_FILE, "res:///com/baidu/android/voicedemo/16k_test.pcm");
        // params.put(SpeechConstant.VAD, SpeechConstant.VAD_DNN);
        // params.put(SpeechConstant.PROP ,20000);
        // params.put(SpeechConstant.PID, 1537); // 中文输入法模型，有逗号
        // 请先使用如‘在线识别’界面测试和生成识别参数。 params同ActivityRecog类中myRecognizer.start(params);

        // 复制此段可以自动检测错误
        (new AutoCheck(getApplicationContext(), new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 100) {
                    AutoCheck autoCheck = (AutoCheck) msg.obj;
                    synchronized (autoCheck) {
                        String message = autoCheck.obtainErrorMessage(); // autoCheck.obtainAllMessage();
                        Log.w("AutoCheckMessage", message);
                    }
                }
            }
        }, enableOffline)).checkAsr(params);
        String json = null; // 可以替换成自己的json
        json = new JSONObject(params).toString(); // 这里可以替换成你需要测试的json
        mAsr.send(event, json, null, 0, 0);
        printLog("输入参数：" + json);
    }

    private void printLog(String text) {
        if (logTime) {
            text += "  ;time=" + System.currentTimeMillis();
        }
        text += "\n";
        Log.i(getClass().getName(), text);
    }


    @Override
    public void initListener() {
        super.initListener();
        mAsr.registerListener(new EventListener() {
            @Override
            public void onEvent(String name, String params, byte[] data, int offset, int length) {
                Toast toast;
                if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_READY)) {
                    toast = Toast.makeText(AiVoiceRecorgnitionActivity.this, "请说话", Toast.LENGTH_SHORT);
                    toast.show();
                } else if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_FINISH)) {
                    toast = Toast.makeText(AiVoiceRecorgnitionActivity.this, "shibie zhong", Toast.LENGTH_SHORT);
                    toast.show();
                }
                String logTxt = "name: " + name;

                if (params != null && !params.isEmpty()) {
                    logTxt += " ;params :" + params;
                }
                if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
                    if (params.contains("\"nlu_result\"")) {
                        if (length > 0 && data.length > 0) {
                            logTxt += ", 语义解析结果：" + new String(data, offset, length);
                        }
                    }
                } else if (data != null) {
                    logTxt += " ;data length=" + data.length;
                }
                toast = Toast.makeText(AiVoiceRecorgnitionActivity.this, logTxt, Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_voice_recorgnition;
    }


    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        String permissions[] = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                Toast toast = Toast.makeText(AiVoiceRecorgnitionActivity.this, "语音识别需要一些权限，请设置权限", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Toast toast;
        if (requestCode == 123)
            toast = Toast.makeText(AiVoiceRecorgnitionActivity.this, "授权成功" + permissions, Toast.LENGTH_SHORT);
        else
            toast = Toast.makeText(AiVoiceRecorgnitionActivity.this, "拒绝授权" + permissions, Toast.LENGTH_SHORT);
        toast.show();
    }

}
